package com.tsingtree.gen.modular.service;

import com.alibaba.fastjson.JSON;
import com.tsingtree.base.db.model.TableFieldInfo;
import com.tsingtree.base.db.util.DbUtil;
import com.tsingtree.gen.core.enums.GenSessionKeyFlags;
import com.tsingtree.gen.modular.model.FieldConfig;
import com.tsingtree.gen.modular.model.GenSessionFieldConfigs;
import com.tsingtree.gen.modular.model.params.SaveFieldConfigParam;
import com.tsingtree.roses.core.config.properties.DruidProperties;
import com.tsingtree.roses.core.util.ToolUtil;
import com.tsingtree.roses.kernel.validator.stereotype.ParamValidator;
import com.tsingtree.sys.modular.system.service.IRedisUtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 代码生成相关逻辑
 *
 * @author jagger
 */
@Service
public class GenerateService {

    @Autowired
    private IRedisUtilService redisUtilService;
    @Autowired
    DruidProperties druidProperties;
    /**
     * 获取某个db容器下，某个表的字段配置
     * <p>
     * 如果之前设置过，则从缓存中拿出
     *
     * @author jagger
     */
    public List<FieldConfig> getTableFieldsConfig(String tableName) {

        //查询session中有无已配置的字段数据，有配置过的直接返回
        String res = redisUtilService.get(GenSessionKeyFlags.TABLE_FIELD_SETTING.name());
        GenSessionFieldConfigs sessionFieldConfigs = JSON.parseObject(res, GenSessionFieldConfigs.class);
        if (sessionFieldConfigs != null && sessionFieldConfigs.containConfigFlag(tableName)) {
            return sessionFieldConfigs.getFieldConfigs(tableName);
        }

        //获取对应表的所有字段
        List<TableFieldInfo> tableFields = DbUtil.getTableFields(tableName, druidProperties);

        //将表的所有字段信息转化为配置信息
        return tableFields.stream().map(i -> {
            FieldConfig fieldConfig = new FieldConfig();
            ToolUtil.copyProperties(i, fieldConfig);
            return fieldConfig;
        }).collect(Collectors.toList());
    }

    /**
     * 设置表的字段配置
     *
     * @author jagger
     */
    @ParamValidator
    public void setTableFieldsConfig(SaveFieldConfigParam saveFieldConfigParam) {

        //从session获取配置
        String res = redisUtilService.get(GenSessionKeyFlags.TABLE_FIELD_SETTING.name());
        GenSessionFieldConfigs sessionFieldConfigs = JSON.parseObject(res, GenSessionFieldConfigs.class);
        if (sessionFieldConfigs == null) {
            sessionFieldConfigs = new GenSessionFieldConfigs();
        }

        //放入session配置树形
        sessionFieldConfigs.getFieldConfigs().put(
                saveFieldConfigParam.getTableName(),
                saveFieldConfigParam.getFieldConfigList());
        redisUtilService.set(GenSessionKeyFlags.TABLE_FIELD_SETTING.name(), JSON.toJSONString(sessionFieldConfigs));
    }

}
